function formatDateTime(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.getFullYear() + '-' +
        String(date.getMonth() + 1).padStart(2, '0') + '-' +
        String(date.getDate()).padStart(2, '0') + ' ' +
        String(date.getHours()).padStart(2, '0') + ':' +
        String(date.getMinutes()).padStart(2, '0') + ':' +
        String(date.getSeconds()).padStart(2, '0');
}

layui.use(['form', 'table', 'layer', 'laydate'], async function () {
    const form = layui.form;
    const table = layui.table;
    const layer = layui.layer;
    const laydate = layui.laydate;

    const token = localStorage.getItem('token');
    const response = await fetch('http://localhost:3000/api/tasks', {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    });

    if (response.status === 403) {
        // Token 无效或过期
        localStorage.removeItem('token');
        window.location.href = 'login.html'; // 跳转到登录页
    }
    if (response.ok) {
        const data = await response.json();
        // console.log(data);
        todos = data;
    } else {
        todos = [];
    }


    let myChart = null;
    let trendChart = null;

    // 初始化日期选择器
    laydate.render({
        elem: '#dueDate'
    });

    function renderTodos(filteredTodos = todos) {
        const todoList = document.getElementById('todoList');
        todoList.innerHTML = '';

        filteredTodos.forEach((todo, index) => {
            console.log(todo);
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${todo.content}</td>
                <td><span class="layui-badge ${getPriorityClass(todo.priority)}">${todo.priority}</span></td>
                <td>${todo.dueDate ? formatDateTime(todo.dueDate) : '-'}</td>
                <td><span class="layui-badge ${todo.isCompleted ? 'layui-bg-green' : 'layui-bg-orange'}">${todo.isCompleted ? '已完成' : '未完成'}</span></td>
                <td>
                    <button class="layui-btn layui-btn-xs ${todo.isCompleted ? 'layui-btn-disabled' : 'layui-btn-normal'}" onclick="toggleTodo(${index})" ${todo.isCompleted ? 'disabled' : ''}>
                        ${todo.isCompleted ? '已完成' : '完成'}
                    </button>
                    <button class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteTodo(${index})">删除</button>
                </td>
            `;
            todoList.appendChild(tr);
        });

        updateCharts();
    }

    function getPriorityClass(priority) {
        switch (priority) {
            case '高': return 'layui-bg-red';
            case '中': return 'layui-bg-blue';
            case '低': return 'layui-bg-gray';
            default: return '';
        }
    }

    window.toggleTodo = function (index) {
        const todo = todos[index];
        todo.isCompleted = !todo.isCompleted;

        // 发送 PUT 请求来更新任务状态
        fetch(`http://localhost:3000/api/tasks/${todo.id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`,
            },
            body: JSON.stringify({
                isCompleted: todo.isCompleted
            })
        })
            .then(response => {
                console.log(response);
                if (response.ok) {
                    return response.json();
                } else {
                    return response.json().then(error => {
                        throw new Error('更新失败: ' + error.error);
                    });
                }
            })
            .then(updatedTodo => {
                // 更新本地的 todos 数组
                todos[index] = updatedTodo;
                renderTodos();
            })
            .catch(error => {
                console.error('更新任务失败:', error);
                layer.msg('网络错误，请稍后重试', { icon: 2 });
            });
    }

    window.deleteTodo = function (index) {
        const todo = todos[index];

        layer.confirm('确定要删除这个待办事项吗？', { icon: 3, title: '提示' }, function (i) {
            // 发送 DELETE 请求来删除任务
            fetch(`http://localhost:3000/api/tasks/${todo.id}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${token}`,
                }
            })
                .then(response => {
                    if (response.ok) {
                        todos.splice(index, 1);  // 从本地 todos 数组中删除任务
                        renderTodos();            // 渲染更新后的任务列表
                        layer.close(i);           // 关闭提示框
                        layer.msg('删除成功', { icon: 1 });
                    } else {
                        return response.json().then(error => {
                            throw new Error('删除失败: ' + error.error);
                        });
                    }
                })
                .catch(error => {
                    console.error('删除任务失败:', error);
                    layer.msg('网络错误，请稍后重试', { icon: 2 });
                });
        });
    };

    form.on('submit(addTodo)', function (data) {
        const { todoItem, priority, dueDate } = data.field;
        if (todoItem) {
            const task = {
                content: todoItem,   // 对应任务内容
                priority: priority,  // 对应优先级
                dueDate: dueDate ? new Date(dueDate).toISOString() : null,    // 对应截止日期
                isCompleted: false,  // 默认未完成
            };
            console.log(task);

            // 发起POST请求
            fetch('http://localhost:3000/api/tasks', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(task)
            })
                .then(function (response) {
                    console.log(response);
                    if (response.ok) {
                        return response.json();  // 解析返回的JSON数据
                    } else {
                        return response.json().then(function (error) {
                            throw new Error('添加失败: ' + error.error);
                        });
                    }
                })
                .then(function (newTask) {
                    todos.push(newTask);  // 将新任务添加到任务列表
                    renderTodos();         // 渲染更新后的任务列表
                    document.getElementById('todoForm').reset();  // 重置表单
                    layer.msg('添加成功', { icon: 1 });
                })
                .catch(function (error) {
                    console.error('添加任务失败:', error);
                    layer.msg('网络错误，请稍后重试', { icon: 2 });
                });
        }
        return false;
    });



    function initCharts() {
        const chartDom = document.getElementById('todoChart');
        const trendDom = document.getElementById('trendChart');
        myChart = echarts.init(chartDom);
        trendChart = echarts.init(trendDom);
        updateCharts();
    }

    function updateCharts() {
        if (!myChart || !trendChart) {
            initCharts();
            return;
        }

        // 更新饼图
        const completedTodos = todos.filter(todo => todo.isCompleted).length;
        const uncompletedTodos = todos.length - completedTodos;

        const pieOption = {
            title: {
                text: '任务完成比例',
                left: 'center',
                textStyle: {
                    color: '#009688'
                }
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '待办事项',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        { value: completedTodos, name: '已完成', itemStyle: { color: '#5FB878' } },
                        { value: uncompletedTodos, name: '未完成', itemStyle: { color: '#FFB800' } }
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        // 计算每日任务数据
        const dailyStats = calculateDailyStats();

        const trendOption = {
            title: {
                text: '任务完成趋势',
                left: 'center',
                textStyle: {
                    color: '#009688'
                }
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['总任务数', '已完成'],
                top: 30
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: dailyStats.dates
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '总任务数',
                    type: 'line',
                    data: dailyStats.totalTasks,
                    itemStyle: {
                        color: '#FFB800'
                    }
                },
                {
                    name: '已完成',
                    type: 'line',
                    data: dailyStats.completedTasks,
                    itemStyle: {
                        color: '#5FB878'
                    }
                }
            ]
        };

        myChart.setOption(pieOption);
        trendChart.setOption(trendOption);
    }

    function calculateDailyStats() {
        // 获取最近7天的日期
        const dates = [];
        const totalTasks = [];
        const completedTasks = [];

        for (let i = 6; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            const dateStr = `${date.getMonth() + 1}/${date.getDate()}`;
            dates.push(dateStr);

            // 统计该日期的任务情况
            const dayTasks = todos.filter(todo => {
                if (!todo.dueDate) return false;
                const todoDate = new Date(todo.dueDate);
                return todoDate.toDateString() === date.toDateString();
            });

            totalTasks.push(dayTasks.length);
            completedTasks.push(dayTasks.filter(task => task.isCompleted).length);
        }

        return { dates, totalTasks, completedTasks };
    }

    // 搜索功能
    document.getElementById('searchInput').addEventListener('input', function (e) {
        const searchTerm = e.target.value.toLowerCase();
        const filteredTodos = todos.filter(todo =>
            todo.content.toLowerCase().includes(searchTerm) ||
            todo.priority.toLowerCase().includes(searchTerm) ||
            (todo.dueDate && todo.dueDate.includes(searchTerm))
        );
        renderTodos(filteredTodos);
    });

    // 初始化图表
    initCharts();
    // 渲染待办事项列表
    renderTodos();

    // 添加窗口大小变化时重绘图表的功能
    window.addEventListener('resize', function () {
        if (myChart) myChart.resize();
        if (trendChart) trendChart.resize();
    });
});
